//
//  ObjectManager.m
//  Words2
//
//  Created by Mathieu on 2/10/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "ObjectManager.h"
#define WordType @"Word"
#import "WordMO.h"
#import "Group.h"
#import "QuizController.h"
#import "GroupsArrayController.h"
#import "WordsAppDelegate.h"
#import "DefinitionMO.h"
#import "Blob.h"


@implementation ObjectManager


- (IBAction)addWord:(id)sender{
	//add the word to the moc
	WordMO* newWord = [NSEntityDescription insertNewObjectForEntityForName:@"Word" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
	[newWord setValue:[[languageArrayController selectedObjects] objectAtIndex:0] forKey:@"language"];
	//place it somewhere
	Group *selectedGroup = [[groupArrayController selectedObjects] objectAtIndex:0];
	if([selectedGroup isManualGroup]){
		[newWord addObject:selectedGroup toToManyRelationshipForKey:@"manualGroups"];
	}
	else{
		[groupArrayController setSelectionToLibrary];
	}
	//add a blank defblob with the capability as the same as the current language
	Blob *blankBlob = [NSEntityDescription insertNewObjectForEntityForName:@"Blob" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
	[blankBlob setValue:newWord forKey:@"word"];
	[blankBlob setValue:[[[NSApp delegate] currentlySelectedLanguage] valueForKey:@"capability"] forKey:@"capabilityKey"];
	[wordsArrayController insertObject:newWord atArrangedObjectIndex:0]; //just pop the object in there for now. It will be
																		// fetched properly next time :-)
}

- (IBAction)removeWords:(id)sender{
	Group *selectedGroup = [[groupArrayController selectedObjects] objectAtIndex:0];
	NSArray *wordsToRemove = [wordsArrayController selectedObjects];
	WordMO *word;
	NSEnumerator *e = [wordsToRemove objectEnumerator];
	if([selectedGroup isManualGroup]){
		while(word = [e nextObject]){
			[wordsArrayController removeObject:word];
			//just remove it from THIS manual group, but leave it attached to the language (so that it shows in the library)
			NSMutableSet *manualGroupSet = [word mutableSetValueForKey:@"manualGroups"];
			[manualGroupSet removeObject:selectedGroup];
		}
	}
	else{ //it's a smart group of some description, only allow deletion if the selection is the library
		if([selectedGroup isThisGroupTheLibrary]){
			//confirm, and remove the words from the language entirely
			while(word = [e nextObject]){
				[wordsArrayController removeObject:word];
				[[[NSApp delegate] managedObjectContext] deleteObject:word]; //delete the object entirely

			}
		}
		//LATER: if the group is a smart group, warn with a sheet and remove it from the library (Permanent deletion).
	}
}



#pragma mark Import / Export Words
	//method which creates a bundle from the selected dictionary, archives it, and saves it as a wordsdict to a specified location.
- (IBAction)exportWords:(id)sender{
	int runResult;
	NSArray *arrayOfWords = [wordsArrayController arrangedObjects];
	NSData *data;
	NSSavePanel *panel = [NSSavePanel savePanel];
	[panel setRequiredFileType:@"wordswords"];
	runResult = [panel runModalForDirectory:NSHomeDirectory() file:nil];
	
	/* if successful, save file under designated name */
	if (runResult == NSOKButton) {
		data = [NSKeyedArchiver archivedDataWithRootObject:arrayOfWords];
		if (![data writeToFile:[panel filename] atomically:YES])
			NSLog(@"Could Note Write to File");
	}
	
	
}
- (IBAction)importWords:(id)sender{
	
	Group * selectedGroup = [[groupArrayController selectedObjects] objectAtIndex:0];
	LanguageMO *selectedLanguage = [[languageArrayController selectedObjects] objectAtIndex:0];
	int runResult;
	NSArray *arrayOfWords;
	NSOpenPanel *panel = [NSOpenPanel openPanel]; //get the open panel
	[panel setAllowedFileTypes:[NSArray arrayWithObject:@"wordswords"]];
	[panel setAllowsMultipleSelection:YES];
	runResult = [panel runModalForDirectory:NSHomeDirectory() file:@""];
	if(runResult == NSOKButton){
		NSArray *filesToOpen = [panel filenames];
		int i, count = [filesToOpen count];
        for (i=0; i<count; i++) {
            NSString *aFile = [filesToOpen objectAtIndex:i];
			arrayOfWords = [NSKeyedUnarchiver unarchiveObjectWithFile:aFile];
			NSEnumerator *e = [arrayOfWords objectEnumerator];
			WordMO *nextWord;
			if([selectedGroup isManualGroup]){
				//add to the manual group AND to the language
				while(nextWord = [e nextObject]){
					[nextWord addObject:selectedGroup toToManyRelationshipForKey:@"manualGroups"];
					[nextWord setValue:selectedLanguage forKey:@"language"];
				}
			}
			if(![selectedGroup isManualGroup]){
				//add to the manual group AND to the language
				while(nextWord = [e nextObject]){
					[nextWord setValue:selectedLanguage forKey:@"language"];
				}
			}
        }
	}		
}

//- (IBAction)addNewTextBlob:(id)sender{
//	DefinitionMO* def = [NSEntityDescription insertNewObjectForEntityForName:@"Definition" inManagedObjectContext:[[NSApp delegate] managedObjectContext]];
//	WordMO * word = [[wordsArrayController selectedObjects] objectAtIndex:0];
//	NSString * capabilityKey = [[[transLangArrayController selectedObjects] objectAtIndex:0] valueForKey:@"capability"];
//	[def setValue:capabilityKey forKey:@"capabilityKey"];
//	[def setValue:word forKey:@"word"];
//}


@end
